import { useAxios } from "@/hooks/useAxios"
import { AxiosTransform } from "./axiosTransform"
import { ContentType } from "../enum"
import { createAxiosRequest } from "./request"
import { authorizationHeader, authorizationValue } from "@/authorization/useAuthorization"
import { isEmpty, message } from "@/utils"
import { checkResponseStatus } from "./axiosError"
import router from "@/router"

const { handleResponseData } = useAxios()

const transform: AxiosTransform = {
    /**
     * @description: 处理请求地址
     */
    beforeRequestHook: (config, options) => {
        const { apiPrefix, modulePrefix } = options
        if (!isEmpty(modulePrefix)) {
            config.url = `${modulePrefix}${config.url}`
        }
        if (!isEmpty(apiPrefix)) {
            config.url = `${apiPrefix}${config.url}`
        }
    },

    /**
     * @description: 添加 token
     */
    requestInterceptors: (config, options) => {
        const token = authorizationValue()
        const withToken = options.withToken
        if (!isEmpty(token) && withToken !== false) {
            config.headers.set(authorizationHeader, token)
        }
    },

    /**
     * @description: 自定义处理返回结果
     */
    transformResponseData: (response, options) => {
        const { isTransformResponse, isReturnNativeResponse } = options
        // 是否返回原生响应头 比如：需要获取响应头时使用该属性
        if (isReturnNativeResponse) {
            return response
        }
        // 是否对返回结果进行处理
        if (!isTransformResponse) {
            return response.data
        }
        const { data } = response
        if (!data) {
            throw new Error("请求出错，请稍候重试")
        }
        return handleResponseData(data, options)
    },

    /**
     * @description: 请求失败处理
     */
    responseInterceptorsCatch: error => {
        console.log(error)

        const { response } = error
        // 请求超时 && 网络错误单独判断，没有 response
        if (error.message.indexOf("timeout") !== -1) {
            message.error("请求超时！请您稍后重试")
        }
        if (error.message.indexOf("Network Error") !== -1) {
            message.error("网络错误！请您稍后重试")
        }
        // 根据服务器响应的错误状态码，做不同的处理
        if (response) {
            checkResponseStatus(response.status)
        }
        // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
        if (!window.navigator.onLine) {
            router.replace("/500")
        }
        return Promise.reject(error)
    }
}

export const http = createAxiosRequest(
    {
        timeout: 2 * 1000,
        baseURL: import.meta.env.VITE_API_URL,
        headers: { "Content-Type": ContentType.json },
        withCredentials: false
    },
    transform,
    {
        isReturnNativeResponse: false,
        isTransformResponse: true,
        ignoreCancelToken: true,
        withToken: true,
        apiPrefix: import.meta.env.VITE_API_PREFIX
    }
)
